﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Radio;
using System.Threading;
using System.Diagnostics;
using System.IO;
using Microsoft.Phone.Shell;
using Microsoft.Phone.BackgroundAudio;

namespace Radio
{
    public partial class MainPage : PhoneApplicationPage
    {
        List<Fm> fmList = new List<Fm>();

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            
            string sl;
            Stream stream = Application.GetResourceStream(new Uri("Res.txt", UriKind.Relative)).Stream;
            using (StreamReader sr = new StreamReader(stream))
                while (!sr.EndOfStream)
                {
                    sl = sr.ReadLine();
                    var fm = new Fm();
                    var temp = sl.Split(';');
                    fm.Name = temp[1];
                    fm.Frequency = temp[0];
                    fmList.Add(fm);
                }

            List.ItemsSource = fmList;

            myRadio = FMRadio.Instance;
            myRadio.CurrentRegion = RadioRegion.Europe;
          
            LoadLast();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            PlayPauseChange(myRadio.PowerMode == RadioPowerMode.On);
            base.OnNavigatedTo(e);
            
        }

        private void LoadLast()
        {

            var last = (Application.Current as App).last;
            if (last == null)
                return;

            Play(last);
        }

        // Create an instance of the radio.
        FMRadio myRadio;

        private void List_Tap(object sender, GestureEventArgs e)
        {
            ListBox list = sender as ListBox;
            Fm selected = list.SelectedItem as Fm;
            Play(selected);
            (Application.Current as App).last = selected;
        }

        private bool CanPlay()
        {
           if (Microsoft.Xna.Framework.Media.MediaPlayer.State == Microsoft.Xna.Framework.Media.MediaState.Playing)
            {
                MessageBox.Show("您的设备正在播放音乐，请您结束或暂停后再使用本应用收听广播");
                Microsoft.Xna.Framework.FrameworkDispatcher.Update();
                return false;
            }
            return true;
        }

        private void Play(Fm selected)
        {
            if (!CanPlay())
                return;

            if (myRadio.PowerMode == RadioPowerMode.Off)
            {
                myRadio.PowerMode = RadioPowerMode.On;
                Thread.Sleep(500);
            }
            //Helper.CheckAntenna();
            myRadio.Frequency = Double.Parse(selected.Frequency);
            this.Dispatcher.BeginInvoke(() =>
            {
                PageTitle.Text = "FM: " + selected.Frequency;
                ApplicationTitle.Text = selected.Name;
            });
            PlayPauseChange(true);
        }

        private void PlayPause_Click(object sender, EventArgs e)
        {

            if (myRadio.PowerMode == RadioPowerMode.On)
            {
                myRadio.PowerMode = RadioPowerMode.Off;
                this.Dispatcher.BeginInvoke(new Action<object>(s =>
                {
                    ApplicationBarIconButton PlayPauseButton = s as ApplicationBarIconButton;
                    PlayPauseButton.Text = "播放";
                    PlayPauseButton.IconUri = new Uri("/Images/appbar.transport.play.rest.png", UriKind.Relative);
                }), sender);
            }
            else
            {
                if (!CanPlay()) return;
                myRadio.PowerMode = RadioPowerMode.On;
                this.Dispatcher.BeginInvoke(new Action<object>(s =>
                {
                    ApplicationBarIconButton PlayPauseButton = s as ApplicationBarIconButton;
                    PlayPauseButton.Text = "暂停";
                    PlayPauseButton.IconUri = new Uri("/Images/appbar.transport.pause.rest.png", UriKind.Relative);
                }), sender);
            }
        }

        private void UpSet_Click(object sender, EventArgs e)
        {
            if (myRadio.PowerMode == RadioPowerMode.On)
            {
                string f = (myRadio.Frequency + 0.1).ToString("0.0");
                double d;
                if (!Double.TryParse(f, out d))
                    return;
                if (d.CompareTo(108d) > 0)
                    return;
                myRadio.Frequency = d;
                Thread.Sleep(100);
                this.Dispatcher.BeginInvoke(() => PageTitle.Text = "FM: " + myRadio.Frequency);
            }
        }

        private void DownSet_Click(object sender, EventArgs e)
        {
            if (myRadio.PowerMode == RadioPowerMode.On)
            {
                string f = (myRadio.Frequency - 0.1).ToString("0.0");
                double d;
                if (!Double.TryParse(f, out d))
                    return;
                if (d.CompareTo(87.5d) < 0)
                    return;
                myRadio.Frequency = d;
                Thread.Sleep(100);
                this.Dispatcher.BeginInvoke(() => PageTitle.Text = "FM: " + myRadio.Frequency);
            }
            
        }
        private void PlayPauseChange(bool isOn)
        {
            if (isOn)
                this.Dispatcher.BeginInvoke(() =>
                {
                    ApplicationBarIconButton PlayPauseButton = ApplicationBar.Buttons[1] as ApplicationBarIconButton;
                    PlayPauseButton.Text = "暂停";
                    PlayPauseButton.IconUri = new Uri("/Images/appbar.transport.pause.rest.png", UriKind.Relative);
                });
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutView.xaml", UriKind.Relative));
        }

     
    }
};